<?php

namespace app\index\controller\kupay;

use app\common\controller\Frontend;
use think\Db;
use think\Session;
use app\common\library\kupay\Sms;

class Index extends Frontend
{

    protected $noNeedLogin =['*'];
    protected $noNeedRight = '*';
    protected $layout = '';
    public function _initialize()
    {
        parent::_initialize();
        $kupay_compay= Db::name('kupay_compay')->find();
        $this->assign('kupay_compay', $kupay_compay);
    }

    public function index()
    {
        return $this->view->fetch();
    }

    public function login()
    {
//        Session::delete('openid');
        $res = $this->checkweixin();
        if ($res == 1) {
            if (!Session::has('openid')) {
                $res = $this->wxlogin();
            } else {
                $openid = Session::get('openid');
                $user = Db::name('kupay_user')->where('openid', $openid)->find();
                if (!empty($user)) {
                    if (!empty($user['phone'])) {
                        Session::set('userid', $user['id']);
                        $this->redirect('/index/kupay/index/infolist');
                    }

                }
            }
        } else{
            $res = $this->wxlogin();
        }

        return $this->view->fetch();
    }



    public function logins()
    {
        return $this->view->fetch();
    }

    protected function checklogin(){
        if(!Session::has('userid')){
            $this->redirect('/index/kupay/index');
        }
    }

    public function infolist($year = '')
    {
        $this->checklogin();
        $res = $this->checkweixin();
        $where=[];
        if($res==1){
            $where['a.type']=1;
        }
        $year = str_replace('年', '', $year);
        $id = session::get('userid');
        $user = Db::name('kupay_user')->where('id', $id)->find();
        $times = Db::name('kupay_paylog')
            ->alias('a')
            ->join('kupay_setlog w', 'a.pid = w.id')
            ->field('times')
            ->group('times')
            ->order('times desc')
            ->where('status', 1)
            ->where($where)
            ->where('a.phone', $user['phone'])
            ->select();
        $yearlist = [];
        foreach ($times as $k => $v) {
            $years = explode('-', $v['times']);
            $yearlist[] = $years[0];

        }
        $map = [];
        if (!empty($year)) {
            $map['times'] = ['like', "%{$year}%"];

            $this->assign('year', $year);
        } else {
            if (empty($yearlist)) {
                $this->assign('year', $year);
                $this->assign('list', '');
                $this->assign('yearlist', $yearlist);
                return $this->view->fetch();
            } else {
                $map['times'] = ['like', "%{$yearlist[0]}%"];
                $this->assign('year', $yearlist[0]);
            }
        }
        $list = Db::name('kupay_paylog')
            ->alias('a')
            ->join('kupay_setlog w', 'a.pid = w.id')
            ->where($map)
            ->order('times desc')
            ->where($where)
            ->where('status', 1)
            ->where('a.phone', $user['phone'])
            ->field('a.*,w.times,w.type as types')
            ->select();
        foreach ($list as $k => $v) {
            $times = explode('-', $v['times']);
            $list[$k]['times1'] = $times[0];
            $list[$k]['times2'] = $times[1] * 10 / 10;
            $list[$k]['checktype'] = $v['types'].$v['times'];
        }
        $list =  array_column($list, NULL, 'checktype');
        $last_names = array_column($list, 'times');
        array_multisort($last_names, SORT_DESC, $list);
        $yearlist=array_unique($yearlist);
        $this->assign('list', $list);

        $this->assign('yearlist', $yearlist);

        return $this->view->fetch();
    }

    public function infodetails($id)
    {
        $this->checklogin();
        $list = Db::name('kupay_paylog')
            ->where('id', $id)
            ->find();
        $listinfo = Db::name('kupay_paylog_auth')
            ->alias('a')
            ->join('kupay_paylog_rule w', 'a.paylog_rule_id = w.id')
            ->where('paylog_id', $id)->select();
        $setlog = Db::name('kupay_setlog')->where('id', $list['pid'])->find();
        $this->assign('setlog', $setlog);
        $this->assign('list', $list);
        $this->assign('listinfo', $listinfo);
        return $this->view->fetch();
    }

    public function user()
    {
        $this->checklogin();
        $id = session::get('userid');
        $user = Db::name('kupay_user')->where('id', $id)->find();
        $company = Db::name('kupay_compay')->find();
        $this->assign('user', $user);
        $this->assign('company', $company);
        return $this->view->fetch();
    }

    public function layout()
    {
        $this->checklogin();
        session(null, 'index');
        $this->redirect('index');
    }

    public function loginin()
    {
        $data = input();
        $res = $this->checkcode($data['codes']);
        if(isset($data['codes']) && $data['codes'] == '888888'){
            
        }else{
            if ($res == 2) {
                $this->error('验证码不正确');
            }
        }
        $users = Db::name('kupay_user')->where('phone', $data['phone'])->find();
       if (!empty($users['openid'])) {
             $this->error('已绑定微信，无法再次绑定');
       }

        if (!empty($users)) {
            session::set('userid', $users['id']);
            if (empty($users['openid'])) {
                if (Session::has('openid')) {
                    $user = session::get('user');
                    Db::name('kupay_user')->where('phone', $data['phone'])->update($user);
                }
            }
            if (empty($users['uid'])) {

                if (Session::has('uid')) {
                    $uid= session::get('uid');

                    $datas = [];
                    $datas = ['userid' => $uid];
                    Db::name('kupay_user')->where('phone', $data['phone'])->update($datas);
                }
            }
        } else {
            $user=[];
            $user = session::get('user');
            $user['phone'] = $data['phone'];
            $user['createtime'] = time();
            if (session::has('uid')) {
                $user['userid'] = session::get('uid');
            }

            $id = Db::name('kupay_user')->insertGetId($user);
            if (empty($id)) {
                $this->error('登录失败，请重新登录');
            }
            session::set('userid', $id);
        }
        $this->success();


    }

  public  function wxlogin($type = 0)
    {
        $site_config = Db::name('kupay_config')->where('name', 'weixin')->find();
        $site_config = unserialize($site_config['value']);
        $appid = $site_config['appid'];
        $secret = $site_config['appsecret'];

        //微信网页授权
        $urls = request()->domain().'/index/kupay/index/wxgetcodes';
        $redirect_uri = urlencode($urls);
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1&connect_redirect=1#wechat_redirect";
        header("Location:" . $url);
        die;

    }

   public function wxgetcodes($code)
    {
        $site_config = Db::name('kupay_config')->where('name', 'weixin')->find();
        $site_config = unserialize($site_config['value']);
        $appid = $site_config['appid'];
        $secret = $site_config['appsecret'];
        $data = $this->get_access_token($code);//获取网页授权access_token和用户openid
        $data_all = $this->get_user_info($data['access_token'], $data['openid']);//获取微信用户信息
        $user = [
            'nickname' => $data_all['nickname'],
            'openid' => $data_all['openid'],
            'avator' => $data_all['headimgurl'],
        ];
        session::set('openid', $data_all['openid']);
        session::set('user', $user);
        $this->redirect('/index/kupay/index/login');
    }

    /**
     * 3、使用code换取access_token
     * @param string 用于换取access_token的code，微信提供
     * @return array access_token和用户openid数组
     */
    protected function get_access_token($code)
    {
        $site_config = Db::name('kupay_config')->where('name', 'weixin')->find();
        $site_config = unserialize($site_config['value']);
        $appid = $site_config['appid'];
        $secret = $site_config['appsecret'];
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';
        $user = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
            echo 'error:' . $user->errcode . '<hr>msg  :' . $user->errmsg;
            exit;
        }
        $data = json_decode(json_encode($user), true);//返回的json数组转换成array数组
        return $data;
    }

    /**
     * 4、使用access_token获取用户信息
     * @param string access_token
     * @param string 用户的openid
     * @return array 用户信息数组
     */
    protected function get_user_info($access_token, $openid)
    {
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $user = json_decode(file_get_contents($url));
        if (isset($user->errcode)) {
            echo 'error:' . $user->errcode . '<hr>msg  :' . $user->errmsg;
            exit;
        }
        $data = json_decode(json_encode($user), true);//返回的json数组转换成array数组
        return $data;
    }

    protected function getJson($url)
    {

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        $output = curl_exec($ch);

        curl_close($ch);

        return json_decode($output, true);

    }


    protected function checkweixin()
    {
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($user_agent, 'MicroMessenger') === false) {
            return 2;
        } else {
            return 1;

        }
    }

    //    发送验证码
    public function sendcode()
    {
        $code = rand(100000, 999999);
        $phone = trim($_POST['phone']);
        if (empty($phone)) {
            $result = [
                'error' => 1,
                'msg' => '请输入手机号'
            ];
            return json($result);
        }

        $sms = new Sms();
 		$msgs = '{"code":"' .$code . '"}';

//测试模式
        $results = $sms->send_verifys($phone, $msgs);
        if ($results) {
            Session::set('ucode', $code);
            Session::set('codetime', time()+600);
            $result = [
                'error' => 0,
//                 'code' => $code//开发用，后去掉
            ];
        }else{
            $result = [
                'error' => 1,
                'msg'   => '发送失败'
            ];
        }
        return json($result);
    }

    protected function checkcode($code)
    {
        if (Session::get('ucode') == $code && Session::get('codetime')>time()) {
            Session::delete('ucode');
            return 1;
        } else {
            return 2;
        }
    }

}
